from flask import *
from AIDetector_pytorch import Detector
import base64
import cv2
import PIL.Image
import datetime
import base64
import time
import plotline
from flask_cors import CORS
from threading import Thread
from queue import Queue
from sql_process import *
from facedetect import *
from utildetector import *
from plotline import *
from ast import literal_eval
import  numpy as np
import json
import global_val
from multiprocessing import Pool
global_val.init()
app = Flask(__name__)
CORS(app, supports_credentials=True)

def base_detect(choicenum):
    filetype = request.form.get('filetype', type=str, default=None)
    if filetype == 'photo':
        img = request.files['file']
        name = str(time.time())
        path = 'static/' + name + '.jpg'
        img.save(path)
        controller = base_detector()
        url = controller.feed_up_image(path, choicenum)
        url = '/static/' + url +'.jpg'
        json_dict = {
            "res_path": url
        }
        return jsonify(json_dict)

    elif filetype == 'video':
        pointArray=[[44, 17], [44, 618], [1216, 17], [1216, 618]]
        if len(global_val.global_pointArray) == 0:
            global_val.set_pointArray('pointArray',pointArray)
        video = request.files['file']
        name = str(time.time())
        path = 'static/' + name + '.mp4'
        video.save(path)
        controller = base_detector()
        result = controller.feed_up_video(path, choicenum)
        return result
    else:
        json_dict = {
            "status": 0,
            "description": "filetype类型为空或类型错误"
        }
    return jsonify(json_dict)


def base_alarm(type):
    connector = mysql_connector().get_connector()
    cur = mysql_connector().get_cur(connector)
    length = mysql_connector().get_last_table_length(cur, connector, type)
    newlength = mysql_connector().get_table_length(cur, connector, type)
    print("上次访问数据库的数据库长度和该次访问数据库的的数据库长度分别为：",length, newlength)
    if newlength > length:
        if type != 'border':
            result = mysql_connector().get_violator_nameandtime(cur, connector, type, newlength - length)
        else:
            result = mysql_connector().get_violator_idandtype(cur, connector, type, newlength - length)
        result0=[]
        result1=[]
        result3={'id':result0,'time':result1}
        for i in result:
            print('i的值',i)
            result0.append(i[0])
            result1.append(i[1])
        print('result1:',result1)
        json_dict = {
            "get_violator_id_status": 1,
            "violator_name": [result3]
        }
        mysql_connector().update_last_table_length(cur, connector, type, newlength)
    else:
        json_dict = {
            "get_violator_id_status": 0,
            "violator_name": {}
        }
    return jsonify(json_dict)

def border_alarm(type):
    connector = mysql_connector().get_connector()
    cur = mysql_connector().get_cur(connector)
    length = mysql_connector().get_last_table_length(cur, connector, type)
    newlength = mysql_connector().get_table_length(cur, connector, type)
    #print(length, newlength)
    if newlength > length:
        if type != 'border':
            result = mysql_connector().get_violator_id(cur, connector, type, newlength - length)
        else:
            result = mysql_connector().get_violator_idandtype(cur, connector, type, newlength - length)
            result0 = []
            result1 = []
            result2 = []
            result3 = []
            result4 = []
            result5 = []
            for i in result:
                if i[1] == 0:
                    result0.append(i[0])
                    result3.append(i[2])
                elif i[1] == 1:
                    result1.append(i[0])
                    result4.append(i[2])
                elif i[1] == 2:
                    result2.append(i[0])
                    result5.append(i[2])
            result0 = {'code':0,'id':result0,'time':result3}
            result1 = {'code':1,'id':result1,'time':result4}
            result2 = {'code':2,'id':result2,'time':result5}
            
        json_dict = {
            "get_violator_id_status": 1,
            "violator_name":[result0,result1,result2],
            }
        mysql_connector().update_last_table_length(cur, connector, type, newlength)
    else:
        json_dict = {
            "get_violator_id_status": 0,
            "violator_name": {}
        }
    return jsonify(json_dict)

@app.route('/get_all_alarm_picture', methods=['GET'])
def get_all_alarm_picture():
    type = request.args.get('type')
    connector = mysql_connector().get_connector()
    cur = mysql_connector().get_cur(connector)
    result = mysql_connector().get_alarm_picture(cur, type)
    res_name = []
    res_time = []
    res_pic = []
    tmp_res = []
    for i in result:
        tmp_dict = {
            "name": i[0],
            "time": i[1],
            "picture": i[2]
        }
        tmp_res.append(tmp_dict)
    json_dict = {
        "status": 0,
        "result": tmp_res
    }
    return jsonify(json_dict)

# 接收file类型的request，访问类型为post，使用时若上传图片应对request中name字段赋值‘photo’，使用时若上传视频应对request中name字段赋值‘video’，response中image表示返回图片，video字段表示返回视频
@app.route('/get_vertex_coordinates', methods=['post'])
def get_vertex_coordinates():
    data = request.get_json()
    mytype = data['type']
    pointArray = data['pointArray']
    global_val.set_pointArray('pointArray',pointArray)
    if type == None or pointArray == None:
        json_dict = {
            "status":0
        }
    else:
        json_dict = {
            "status":1
        }
    return jsonify(json_dict)
@app.route('/phone_detect', methods=['post'])
def phone_detect():
    choicenum = 3
    return base_detect(choicenum)

@app.route('/sundry_detect', methods=['post'])
def sundry_detect():
    choicenum = 6
    return sundry_detect(choicenum)

@app.route('/hat_detect', methods=['post'])
def hat_detect():
    choicenum = 1
    return base_detect(choicenum)

@app.route('/reflect_detect', methods=['post'])
def reflect_detect():
    choicenum = 2
    return base_detect(choicenum)

@app.route('/fire_detect', methods=['post'])
def fire_detect():
    choicenum = 4
    return base_detect(choicenum)

@app.route('/smoking_detect', methods=['post'])
def smoking_detect():
    choicenum = 5
    return base_detect(choicenum)

@app.route('/sleep_detect', methods=['post'])
def sleep_detect():
    choicenum = 7
    return base_detect(choicenum)
'''
@app.route('/speed_detect',methods=['post'])
def speed_detect():
    choicenum = 9
    return base_detect(choicenum)
'''

# 接收file类型的request，访问类型为post，使用时若上传图片应对request中name字段赋值‘photo’，使用时若上传视频应对request中name字段赋值‘video’，response中image表示返回图片，video字段表示返回视频
@app.route('/face_detect', methods=['post'])
def face_detect():
    filetype = request.form.get('filetype', type=str, default=None)
    if filetype == 'photo':
        img = request.files['file']
        name = str(time.time())
        path = 'static/' + name + '.jpg'
        img.save(path)
        controller = facedetect()
        url = controller.face_image_detect(path)
        url = '/static/' + url + '.jpg'
        json_dict = {
            "res_path": url
        }
        return jsonify(json_dict)
    elif filetype == 'video':
        video = request.files['file']
        name = str(time.time())
        path = 'static/' + name + '.mp4'
        video.save(path)
        controller = facedetect()
        url = controller.face_video_detect(path)
        url = '/static/' + url + '.avi'
        json_dict = {
            "res_path": url
        }
        return jsonify(json_dict)
    else:
        json_dict = {
            "status": 100000,
            "description": "filetype类型为空或类型错误"
        }
    return jsonify(json_dict)

@app.route('/speed_detect_realtime',methods = ['GET'])
def speed_detect_realtime():
    if request.args.get("monitor_id") == None:
        length = 0
        path = 'video/cars.mp4'
        #path = request.args.get("monitor_id")
        model = base_detector()
        framenum = 0
        choicenum = 9
        det = Detector(choicenum)
        cap = cv2.VideoCapture(path)
        connector = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(connector)
        return Response(speed_gen(model, det, cap, choicenum, framenum, cur, connector, length),
                        mimetype='multipart/x-mixed-replace; boundary=frame')
    else:
        length = 0
        path = request.args.get("monitor_id")
        model = base_detector()
        framenum = 0
        choicenum = 9
        det = Detector(choicenum)
        cap = cv2.VideoCapture(path)
        connector = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(connector)
        return Response(speed_gen(model, det, cap, choicenum, framenum, cur, connector, length),
                        mimetype='multipart/x-mixed-replace; boundary=frame')

def speed_gen(model, det, cap, choicenum, framenum, cur, connector,length):
    while cap.isOpened():
        ret, im = cap.read()
        if ret is True:
            frame= model.get_speed_frame(det, cap, choicenum, im, framenum, ret, cur, connector, length)
            yield (b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame)
            framenum = framenum + 1
        else:
            cap.release()
            break
        
@app.route('/sundry_detect_realtime',methods = ['GET'])
def sundry_detect_realtime():
    if request.args.get("monitor_id") == None:
        path = 'video/sundry3.mp4'
        model = base_detector()
        framenum = 0
        choicenum = 6
        cap = cv2.VideoCapture(path)
        connector = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(connector)
        return Response(sundry_gen(model, cap, choicenum, framenum, cur, connector),
                    mimetype='multipart/x-mixed-replace; boundary=frame')
    else:
        path = request.args.get("monitor_id")
        model = base_detector()
        framenum = 0
        choicenum = 6
        cap = cv2.VideoCapture(path)
        return Response(sundry_gen(model, cap, choicenum, framenum),
                        mimetype='multipart/x-mixed-replace; boundary=frame')


def sundry_gen(model, cap, choicenum, framenum, cur, connector):
    while cap.isOpened():
        ret, im = cap.read()
        if ret is True:
            frame = model.get_sundry_frame(choicenum, im, framenum, ret, cur, connector)
            yield (b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame)
            framenum = framenum + 1
        else:
            cap.release()
            break


@app.route('/phone_detect_realtime',methods = ['GET'])
def phone_detect_realtime():
    if request.args.get("monitor_id") == None:
        #path = request.args.get("monitor_id")
        length = 0
        path = 'video/phone.mp4'
        # video.save(path)
        model = base_detector()
        framenum = 0
        choicenum = 3
        det = Detector(choicenum)
        cap = cv2.VideoCapture(path)
        connector = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(connector)
        return Response(phone_gen(model, det, cap, choicenum, framenum, cur, connector, length),
                        mimetype='multipart/x-mixed-replace; boundary=frame')
    else:
        path = request.args.get("monitor_id")
        length = 0
        model = base_detector()
        framenum = 0
        choicenum = 3
        det = Detector(choicenum)
        cap = cv2.VideoCapture(path)
        connector = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(connector)
        return Response(phone_gen(model, det, cap, choicenum, framenum, cur, connector, length),
                        mimetype='multipart/x-mixed-replace; boundary=frame')


def phone_gen(model, det, cap, choicenum, framenum, cur, connector, length):
    while cap.isOpened():
        ret, im = cap.read()
        if ret is True:
            frame = model.get_frame(det, cap, choicenum, im, framenum, ret, cur, connector, length)
            yield (b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame)
            framenum = framenum + 1
        else:
            cap.release()
            break

@app.route('/sleep_detect_realtime',methods = ['GET'])
def sleep_detect_realtime():
    if request.args.get("monitor_id") == None:
        #path = request.args.get("monitor_id")
        path = 'video/sleep3.mp4'
        length = 0
        # video.save(path)
        model = base_detector()
        framenum = 0
        choicenum = 7
        det = Detector(choicenum)
        cap = cv2.VideoCapture(path)
        connector = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(connector)
        return Response(sleep_gen(model, det,  cap, choicenum, framenum, cur, connector, length),
                        mimetype='multipart/x-mixed-replace; boundary=frame')
    else:
        path = request.args.get("monitor_id")
        length = 0
        # video.save(path)
        model = base_detector()
        framenum = 0
        choicenum = 7
        det = Detector(choicenum)
        cap = cv2.VideoCapture(path)
        connector = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(connector)
        return Response(sleep_gen(model, det,  cap, choicenum, framenum, cur, connector, length),
                        mimetype='multipart/x-mixed-replace; boundary=frame')

def sleep_gen(model, det, cap, choicenum, framenum, cur, connector, length):
    while cap.isOpened():
        ret, im = cap.read()
        if ret is True:
            frame = model.get_frame(det,  cap, choicenum, im, framenum, ret, cur, connector, length)
            yield (b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame)
            framenum = framenum + 1
        else:
            cap.release()
            break
            
@app.route('/hat_detect_realtime',methods = ['GET'])
def hat_detect_realtime():
    if request.args.get("monitor_id") == None:
        #path = request.args.get("monitor_id")
        path = 'video/hatvideo.mp4'
        length = 0
        # video.save(path)
        model = base_detector()
        framenum = 0
        choicenum = 1
        det = Detector(choicenum)
        cap = cv2.VideoCapture(path)
        connector = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(connector)
        return Response(hat_gen(model, det,  cap, choicenum, framenum, cur, connector, length),
                        mimetype='multipart/x-mixed-replace; boundary=frame')
    else:
        
        loop = int(request.args.get("loop"))

        
        path = request.args.get("monitor_id")
        length = 0
        # video.save(path)
        model = base_detector()
        framenum = 0
        choicenum = 1
        det = Detector(choicenum)
        cap = cv2.VideoCapture(path)
        connector = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(connector)
        return Response(hat_gen(model, det,  cap, choicenum, framenum, cur, connector, length,loop),
                        mimetype='multipart/x-mixed-replace; boundary=frame')


def hat_gen(model, det,  cap, choicenum, framenum, cur, connector, length,loop=0):
    while cap.isOpened():
        
        i = 0

        while (i < loop):
            cap.grab()
            i = i + 1
        
        ret, im = cap.read()
        if ret is True:
            frame = model.get_frame(det,  cap, choicenum, im, framenum, ret, cur, connector, length)
            yield (b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame)
            framenum = framenum + 1
        else:
            cap.release()
            break

@app.route('/reflect_detect_realtime',methods = ['GET'])
def reflect_detect_realtime():
    if request.args.get("monitor_id") == None:
        #path = request.args.get("monitor_id")
        path = 'video/reflect2.mp4'
        length = 0
        # video.save(path)
        model = base_detector()
        framenum = 0
        choicenum = 2
        det = Detector(choicenum)
        cap = cv2.VideoCapture(path)
        connector = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(connector)
        return Response(reflect_gen(model, det,  cap, choicenum, framenum, cur, connector, length),
                        mimetype='multipart/x-mixed-replace; boundary=frame')
    else:
        path = request.args.get("monitor_id")
        length = 0
        # video.save(path)
        model = base_detector()
        framenum = 0
        choicenum = 2
        det = Detector(choicenum)
        cap = cv2.VideoCapture(path)
        connector = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(connector)
        return Response(reflect_gen(model, det,  cap, choicenum, framenum, cur, connector, length),
                        mimetype='multipart/x-mixed-replace; boundary=frame')


def reflect_gen(model, det,cap, choicenum, framenum, cur, connector, length):
    while cap.isOpened():
        ret, im = cap.read()
        if ret is True:
            frame = model.get_frame(det, cap, choicenum, im, framenum, ret, cur, connector, length)
            yield (b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame)
            framenum = framenum + 1
        else:
            cap.release()
            break


@app.route('/fire_detect_realtime',methods = ['GET'])
def fire_detect_realtime():
    if request.args.get("monitor_id") == None:
        #path = request.args.get("monitor_id")
        path = 'video/firevideo.mp4'
        length = 0
        # video.save(path)
        model = base_detector()
        framenum = 0
        choicenum = 4
        det = Detector(choicenum)
        cap = cv2.VideoCapture(path)
        connector = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(connector)
        return Response(fire_gen(model, det,  cap, choicenum, framenum, cur, connector, length),
                        mimetype='multipart/x-mixed-replace; boundary=frame')
    else:
        path = request.args.get("monitor_id")
        length = 0
        # video.save(path)
        model = base_detector()
        framenum = 0
        choicenum = 4
        det = Detector(choicenum)
        cap = cv2.VideoCapture(path)
        connector = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(connector)
        return Response(fire_gen(model, det,  cap, choicenum, framenum, cur, connector, length),
                        mimetype='multipart/x-mixed-replace; boundary=frame')




def fire_gen(model, det, cap, choicenum, framenum, cur, connector, length):
    while cap.isOpened():
        ret, im = cap.read()
        if ret is True:
            frame = model.get_frame(det,cap, choicenum, im, framenum, ret, cur, connector, length)
            yield (b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame)
            framenum = framenum + 1
        else:
            cap.release()
            break


@app.route('/smoking_detect_realtime',methods = ['GET'])
def smoking_detect_realtime():
    if request.args.get("monitor_id") == None:
        #path = request.args.get("monitor_id")
        path = 'video/smoking.mp4'
        length = 0
        # video.save(path)
        model = base_detector()
        framenum = 0
        choicenum = 5
        det = Detector(choicenum)
        cap = cv2.VideoCapture(path)
        connector = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(connector)
        return Response(smoking_gen(model, det, cap, choicenum, framenum, cur, connector, length),
                        mimetype='multipart/x-mixed-replace; boundary=frame')
    else:
        path = request.args.get("monitor_id")
        length = 0
        # video.save(path)
        model = base_detector()
        framenum = 0
        choicenum = 5
        det = Detector(choicenum)
        cap = cv2.VideoCapture(path)
        connector = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(connector)
        return Response(smoking_gen(model, det, cap, choicenum, framenum, cur, connector, length),
                        mimetype='multipart/x-mixed-replace; boundary=frame')


def smoking_gen(model, det, cap, choicenum, framenum, cur, connector, length):
    while cap.isOpened():
        ret, im = cap.read()
        if ret is True:
            frame = model.get_frame(det, cap, choicenum, im, framenum, ret, cur, connector, length)
            yield (b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame)
            framenum = framenum + 1
        else:
            cap.release()
            break


@app.route('/face_detect_realtime',methods = ['GET'])
def face_detect_realtime():
    if request.args.get("monitor_id") == None:
        #path = request.args.get("monitor_id")
        path = 'video/zhangxueyou.mp4'
        # video.save(path)
        model = facedetect()
        framenum = 0
        choicenum = 1
        det = Detector(choicenum)
        retinaface = Retinaface()
        cap = cv2.VideoCapture(path)
        return Response(face_gen(model, det, retinaface, cap, choicenum, framenum),
                        mimetype='multipart/x-mixed-replace; boundary=frame')
    else:
        path = request.args.get("monitor_id")
        # video.save(path)
        model = facedetect()
        framenum = 0
        choicenum = 1
        det = Detector(choicenum)
        retinaface = Retinaface()
        cap = cv2.VideoCapture(path)
        return Response(face_gen(model, det, retinaface, cap, choicenum, framenum),
                        mimetype='multipart/x-mixed-replace; boundary=frame')
    
def face_gen(model, det, retinaface, cap, choicenum, framenum):
    while cap.isOpened():
        ret, im = cap.read()
        if ret is True:
            frame = model.get_frame(det, retinaface, cap, choicenum, im, framenum, ret)
            yield (b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame)
            framenum = framenum + 1
        else:
            cap.release()
            break


@app.route('/hat_alarm_realtime')
def hat_alarm_realtime():
    return base_alarm('hat')


@app.route('/phone_alarm_realtime')
def phone_alarm_realtime():
    return base_alarm('phone')


@app.route('/reflect_alarm_realtime')
def reflect_alarm_realtime():
    return base_alarm('reflect')


@app.route('/fire_alarm_realtime')
def fire_alarm_realtime():
    return base_alarm('fire')


@app.route('/smoking_alarm_realtime')
def smoking_alarm_realtime():
    return base_alarm('smoking')

@app.route('/border_alarm_realtime')
def border_alarm_realtime():
    return border_alarm('border')

@app.route('/sleep_alarm_realtime')
def sleep_alarm_realtime():
    return base_alarm('sleep')

@app.route('/sundry_alarm_realtime')
def sundry_alarm_realtime():
    return base_alarm('sundry')

@app.route('/get_detect_frame',methods=['GET'])
def get_detect_frame():
    if request.args.get("monitor_id") is None:
        if request.args.get("type") == "hat":
            path = 'video/hatvideo.mp4'
            print('hat')
        elif request.args.get("type") == "reflect":
            path = 'video/reflect2.mp4'
            print('reflect')
        elif request.args.get("type") == "phone":
            path = 'video/phone.mp4'
            print("phone")
        elif request.args.get("type") == "fire":
            path = 'video/firevideo.mp4'
            print("fire")
        elif request.args.get("type") == "smoking":
            path = 'video/smoking.mp4'
            print('smoking')
        elif request.args.get("type") == "sundry":
            path = 'video/sundry3.mp4'
            print('sundry')
        elif request.args.get("type") == "speed":
            path = 'video/cars.mp4'
        elif request.args.get("type") == "fence":
            path = 'video/test.mp4'
        else:
            path = 'video/sleep3.mp4'
            print('sleep')
        cap = cv2.VideoCapture(path)
        name = str(time.time()) + '.jpg'
        path = 'static/' + name
        print("当前路径是:", path)
        ret, im = cap.read()
        cv2.imwrite(path, im)
        url = '/static/' + name
        json_dict = {
            "status": 1,
            "URL": url
        }
    else:
        path = request.args.get("monitor_id")
        cap = cv2.VideoCapture(path)
        name = str(time.time()) + '.jpg'
        path = 'static/' + name
        print("当前路径是:", path)
        ret, im = cap.read()
        cv2.imwrite(path, im)
        url = '/static/' + name
        json_dict = {
            "status": 1,
            "URL": url
        }
    return jsonify(json_dict)

@app.route('/get_current_frame',methods = ['GET'])
def get_current_frame():
    if request.args.get("monitor_id") == None:
        #path = request.args.get("monitor_id")
        path = 'video/test.mp4'
        cap = cv2.VideoCapture(path)
        name = str(time.time()) + '.jpg'
        path =  'static/'+name
        print("当前路径是:",path)
        ret, im = cap.read()
        cv2.imwrite(path, im)
        url = '/static/' + name
        json_dict = {
            "status": 1,
            "URL": url
        }
    else:
        path = request.args.get("monitor_id")
        #path = 'video/围栏.mp4'
        cap = cv2.VideoCapture(path)
        if cap.isOpened():
            name = str(time.time())
            path = 'static/' + name + '.jpg'
            ret, im = cap.read()
            cv2.imwrite(path, im)
            url = '/static/' + name +'.jpg'
            json_dict = {
                "status": 1,
                "URL": url
            }
        else:
            url = ''
            json_dict = {
                "status": 0,
                "URL": url
            }
    return jsonify(json_dict)



@app.route('/border_detect_realtime',methods = ['GET','POST'])
def border_detect_realtime():
    if request.method == 'GET':
        time1 = time.time()
        linedraw = plotline()
        monitor_id = request.args.get("monitor_id")
        conn = mysql_connector().get_connector()
        cur = mysql_connector().get_cur(conn)
        linelist,pointlist,draw_index,typelist,linetype = mysql_connector().get_monitor_border_config(cur,conn,monitor_id)
        print(linetype)
        if linetype == 'rect':
            pointlist = literal_eval(pointlist)
            linelist = literal_eval(linelist)
            linedraw.plot['pointlist'] = list(pointlist)
            linedraw.plot['linelist'] = list(linelist)
            draw_index = literal_eval(draw_index)
            linedraw.plot['draw_index'] = list(draw_index)
            typelist = literal_eval(typelist)
            linedraw.plot['typelist'] = list(typelist)
            if monitor_id == '1':
                path = 'video/test.mp4'
            else:
                path = monitor_id
            length = 0
            model = base_detector()
            framenum = 0
            choicenum = 10
            det = Detector(choicenum)
            cap = cv2.VideoCapture(path)
            connector = mysql_connector().get_connector()
            cur = mysql_connector().get_cur(connector)
            return Response(border_gen_rect(model, det, cap, choicenum, linedraw,framenum,connector,cur,length,time1),
                            mimetype='multipart/x-mixed-replace; boundary=frame')
        else:
            pointlist = literal_eval(pointlist)
            linelist = literal_eval(linelist)
            linedraw.plot['pointlist'] = list(pointlist)
            linedraw.plot['linelist'] = list(linelist)
            draw_index = literal_eval(draw_index)
            linedraw.plot['draw_index'] = list(draw_index)
            typelist = literal_eval(typelist)
            linedraw.plot['typelist'] = list(typelist)
            if monitor_id == '1':
                path = 'video/test.mp4'
            else:
                path = monitor_id
            length = 0
            model = base_detector()
            framenum = 0
            choicenum = 10
            det = Detector(choicenum)
            cap = cv2.VideoCapture(path)
            connector = mysql_connector().get_connector()
            cur = mysql_connector().get_cur(connector)
            return Response(border_gen_line(model, det, cap, choicenum, linedraw,framenum,connector,cur,length,time1),
                            mimetype='multipart/x-mixed-replace; boundary=frame')
                        
    elif request.method == 'POST':
        linedraw = plotline()
        data = request.get_json()
        linetype = data["linetype"]
        pointlist = data["pointList"]
        linelist = data["lineList"]
        draw_index = data["draw_index"]
        typelist = data["typeList"]
        monitor_id = data["monitor_id"]
        new_monitor_flag  = data["new_monitor_flag"]
        if new_monitor_flag == 1:
            print(type(pointlist))
            templinelist = linelist
            linelist = list()
            temppointlist = pointlist
            pointlist = list()
            for i in temppointlist:
                pointlist.append(tuple(i))
            for i in templinelist:
                linelist.append(tuple(i))
            pointlist = str(pointlist)
            linelist = str(linelist)
            draw_index = str(draw_index)
            typelist = str(typelist)
            conn = mysql_connector().get_connector()
            cur = mysql_connector().get_cur(conn)
            status = mysql_connector().insert_monitor_border_config(cur,conn,monitor_id,linelist,pointlist,draw_index,typelist,linetype)
            json_dict = {
                "status": status,
                "description": "status为1,执行成功,statusw为0,执行失败"
            }
        elif new_monitor_flag == 0:
            print(type(pointlist))
            templinelist = linelist
            linelist = list()
            temppointlist = pointlist
            pointlist = list()
            for i in temppointlist:
                pointlist.append(tuple(i))
            for i in templinelist:
                linelist.append(tuple(i))
            pointlist = str(pointlist)
            linelist = str(linelist)
            draw_index = str(draw_index)
            typelist = str(typelist)
            print(pointlist,type(pointlist))
            print(linelist,type(linelist))
            print(draw_index,type(draw_index))
            print(typelist,type(typelist))
            conn = mysql_connector().get_connector()
            cur = mysql_connector().get_cur(conn)
            status = mysql_connector().update_monitor_border_config(cur,conn,monitor_id,linelist,pointlist,draw_index,typelist,linetype)
            json_dict = {
                "status": status,
                "description": "status为1,执行成功,statusw为0,执行失败"
            }
        return jsonify(json_dict)

def border_gen_rect(model, det,  cap, choicenum, linedraw,framenum,connector,cur,length,time1):
    while cap.isOpened():
        ret, im = cap.read()
        if ret is True :
            frame = model.get_borderframe_rect(det,  cap, choicenum, im, framenum, ret, linedraw, cur, connector,length)
            yield (b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame)
            framenum = framenum + 1
        else:
            time2 = time.time()
            #ret2, jpeg = cv2.imencode('.jpg', frame)
            print("每帧处理的用时:",time2-time1)
            cap.release()
            break
            
def border_gen_line(model, det,  cap, choicenum, linedraw,framenum,connector,cur,length,time1):
    while cap.isOpened():
        ret, im = cap.read()
        if ret is True :
            frame = model.get_borderframe_line(det,  cap, choicenum, im, framenum, ret, linedraw, cur, connector,length)
            yield (b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame)
            framenum = framenum + 1
        else:
            time2 = time.time()
            #ret2, jpeg = cv2.imencode('.jpg', frame)
            print("没帧处理1次的用时:",time2-time1)
            cap.release()
            break

if __name__ == '__main__':
    app.run(host='0.0.0.0',
            port=6006,
            debug=True
           )
